import {getRequest} from "@/utils/config";

export const initMenus=(router,store)=>{ //初始化菜单时 传入路由配置和vuex的配置
    if (store.state.routers.length>0){ //如果store中已经存在路由表则直接返回
        return;
    }

    getRequest('/system/config/menus').then(data=>{
        if (data){
            let fmtRouters = formatRoutes(data); //创建格式化数据的函数
            router.addRoutes(fmtRouters); //写入路由表
            store.commit('initRouters',fmtRouters);//写入vuex
        }

    })
}

export const formatRoutes = (routes) => {
    let fmRoutes = [];
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            meta,
            iconCls,
            children
        } = router;
        if (children && children instanceof Array) {
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            meta: meta,
            children: children,
            component(resolve) {

              require(['../views/' + component + '.vue'], resolve);

            }
        }
        fmRoutes.push(fmRouter);
    })
    return fmRoutes;
}